//
//  KeyChainStore.m
//  XYDIDCardText
//
//  Created by Mickey Yin on 2021/12/22.
//

#import "KeyChainStore.h"

@implementation KeyChainStore

+ (NSMutableDictionary*)getKeychainQuery:(NSString*)service {

    return[NSMutableDictionary dictionaryWithObjectsAndKeys:(id)kSecClassGenericPassword,(id)kSecClass, service,(id)kSecAttrService, service,(id)kSecAttrAccount,(id)kSecAttrAccessibleAfterFirstUnlock,(id)kSecAttrAccessible, nil];
}

+ (void)save:(NSString*)service data:(id)data{
    
    NSMutableDictionary*keychainQuery = [self getKeychainQuery:service];
    
    SecItemDelete((CFDictionaryRef)keychainQuery);

    [keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data]forKey:(id)kSecValueData];
    
    SecItemAdd((CFDictionaryRef)keychainQuery,NULL);
}

+ (id)load:(NSString*)service {

    NSString * idret =nil;
    
    NSMutableDictionary*keychainQuery = [self getKeychainQuery:service];
    
    [keychainQuery setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData];

    [keychainQuery setObject:(id)kSecMatchLimitOne forKey:(id)kSecMatchLimit];

    CFDataRef keyData =NULL;

    if(SecItemCopyMatching((CFDictionaryRef)keychainQuery,(CFTypeRef*)&keyData) ==noErr) {
        
        @try {
            
            idret =[NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData*)keyData];
    
        } @catch(NSException *e) {
        
            NSLog(@"Unarchiveof %@ failed: %@", service, e);
   
        } @finally {
   
        }
    }
   
    if(keyData) {
        
        CFRelease(keyData);
    }

    return idret;
}

+ (void)deleteKeyData:(NSString*)service {

    NSMutableDictionary*keychainQuery = [self getKeychainQuery:service];
    SecItemDelete((CFDictionaryRef)keychainQuery);
}


@end
